package com.ruoyi.doudian.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.doudian.service.DoudianAuthService;
import com.ruoyi.doudian.service.GoodsService;
import com.ruoyi.doudian.utils.Http;
import com.ruoyi.doudian.vo.AccessTokenVO;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.DoudianUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;

/**
 * @author X
 * @version 1.0
 * @ClassName GoodsServiceImpl
 * @description
 * @date 2020/11/2
 **/
@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private DoudianAuthService doudianAuthService;
    @Autowired
    private RedisCache redisCache;

    /***
     * 获取店铺商品列表
     * @param page
     * @param size
     * @return
     */
    @Override
    public String getGoodsList(int page, int size) throws UnsupportedEncodingException {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        DoudianUser doudianUser = doudianAuthService.getDoudianUserByUserId(userId);
        String shopId = doudianUser.getShopId();

        Object cacheObject = redisCache.getCacheObject(shopId);
        if (ObjectUtil.isNull(cacheObject)) {
            return null;
        }
        String cacheStr = JSON.toJSONString(cacheObject);
        AccessTokenVO accessTokenVO = JSON.parseObject(cacheStr, AccessTokenVO.class);

        Date date = new Date();
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = dateFormat1.format(date);
        String format2 = dateFormat2.format(date);

        //有序 业务参数
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("page", String.valueOf(page));
        linkedHashMap.put("size", String.valueOf(size));
        String mapStr = JSON.toJSONString(linkedHashMap);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(linkedHashMap));
        String encode = URLEncoder.encode(jsonObject.toJSONString(), "UTF-8");

        String app_key = "6863250841932285454";
        String access_token = accessTokenVO.getAccessToken();

        String method = "product.list";
        //拼接url
        String url = "https://openapi-fxg.jinritemai.com/product/list?app_key=" + app_key + "&access_token=" + access_token + "&method=product.list=" + encode + "&timestamp=" + format1 + "&v=2&sign=" + sign(app_key, mapStr, method, format2);

        Http http = new Http();
        String result = http.doGet(url);
        System.out.println(result);
        return result;
    }

    /***
     * 获取商品信息
     * @param productId
     * @return
     */
    @Override
    public String getGoodsByProductId(String productId) throws UnsupportedEncodingException {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        DoudianUser doudianUser = doudianAuthService.getDoudianUserByUserId(userId);
        String shopId = doudianUser.getShopId();

        Object cacheObject = redisCache.getCacheObject(shopId);
        if (ObjectUtil.isNull(cacheObject)) {
            return null;
        }
        String cacheStr = JSON.toJSONString(cacheObject);
        AccessTokenVO accessTokenVO = JSON.parseObject(cacheStr, AccessTokenVO.class);

        Date date = new Date();
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = dateFormat1.format(date);
        String format2 = dateFormat2.format(date);

        //有序 业务参数
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("product_id", productId);
        String mapStr = JSON.toJSONString(linkedHashMap);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(linkedHashMap));
        String encode = URLEncoder.encode(jsonObject.toJSONString(), "UTF-8");

        String app_key = "6863250841932285454";
        String access_token = accessTokenVO.getAccessToken();

        String method = "product.detail";
        //拼接url
        String url = "https://openapi-fxg.jinritemai.com/product/list?app_key=" + app_key + "&access_token=" + access_token + "&method=product.detail=" + encode + "&timestamp=" + format1 + "&v=2&sign=" + sign(app_key, mapStr, method, format2);

        Http http = new Http();
        String result = http.doGet(url);
        System.out.println(result);
        return result;
    }


    public String sign(String app_key, String mapStr, String method, String format2) {
        String secret = "8963b551-bd04-4be5-b02b-2e82ee0fccdb";
        String str = secret + "app_key" + app_key + "method" + method + "param_json" + mapStr + "timestamp" + format2 + "v2" + secret;
        String res = stringToMD5(str);
        return res;
    }

    public static String stringToMD5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(
                    plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有这个md5算法！");
        }
        StringBuilder md5code = new StringBuilder(new BigInteger(1, secretBytes).toString(16));
        while (md5code.length() < 32) {
            md5code.insert(0, "0");
        }
        return md5code.toString();
    }
}
